﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Imdb;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
using System.Threading;

namespace MoviesManager
{
    public partial class MainMovieForm : Form
    {
        string moviesFolderPath = @"E:\MoviesMangager";
        Imdb.Services Imdb = new Services();
        FiltersCollection MFiltersCollection = new FiltersCollection();
        VMovieCollection VMCollection = new VMovieCollection();

        VMovie CurrentMovie = new VMovie();
        Movie SelectedMovie = new Movie();

        public MainMovieForm()
        {
            InitializeComponent();
            Imdb.FoundMovies += new Imdb.Services.FoundMoviesEventHandler(Imdb_FoundMovies);
            //Imdb.MovieParsed += new Imdb.Services.MovieParsedEventHandler(Imdb_MovieParsed);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FillMoviesFolders();
            LoadFilters();
        }

        private void FillMoviesFolders()
        {
            DirectoryInfo folder = new DirectoryInfo(moviesFolderPath);
            string[] files;

            if (folder.Exists)
            {
                string[] Folder;
                Folder = Directory.GetDirectories(moviesFolderPath);
                foreach (string FolderName in Folder)
                {
                    FileInfo fi = new FileInfo(FolderName);

                    VMovie mFolder = new VMovie();

                    mFolder.FullPath = fi.FullName;
                    mFolder.ID = fi.Name.GetHashCode();
                    mFolder.OriginalName = fi.Name;
                    mFolder.NewName = fi.Name;
                    mFolder.MovieSynhName = fi.Name;
                    mFolder.CurrentName = fi.Name;

                    files = Directory.GetFiles(fi.FullName);
                    foreach (var item in files)
                    {

                        FileInfo fileNameInfo = new FileInfo(item);
                        mFolder.MovieFiles.Add(fileNameInfo);
                        if (Path.GetFileName(item) == "vmconf")
                        {
                            HelperClass.LoadMovieFromConf(ref mFolder, fileNameInfo);
                        }
                    }

                    //mFolder.ImdbSynchronisationDone += new VMovie.ImdbSynchronisation(IMDBSynchDone);
                    VMCollection.Add(mFolder);

                }
            }

            ReBindMovies();
        }

        private void ReBindMovies()
        {
            movieFolderBindingSource.DataSource = null;
            movieFolderBindingSource.DataSource = VMCollection;
        }

        private void ReBindFilters()
        {
            movieFilters.DataSource = null;
            movieFilters.DataSource = MFiltersCollection;
            movieFilterTypes.DataSource = Enum.GetValues(typeof(FilterType));
        }

        private void btnBrowseMovie_Click(object sender, EventArgs e)
        {
            if (dialogMovieBrowser.ShowDialog() == DialogResult.OK)
                moviesFolderPath = dialogMovieBrowser.SelectedPath;

            txtMoviePath.Text = moviesFolderPath;
            FillMoviesFolders();


        }



        private void btnSearch_Click(object sender, EventArgs e)
        {
            Imdb.FindMovie(txtSearch.Text.Replace('.', ' '));
        }

        

        void Imdb_FoundMovies(Imdb.MoviesResultset M)
        {
            var temp = ((VMovie)VMCollection.FirstOrDefault(p => p.MovieSynhName.ToLower() == M.SearchedMovieName.ToLower()));
            if (temp != null)
            {
                temp.MoviesIMDBResultset = M;
                temp.TryToChooceMovie();
            }
        }

        private void FillIfExcist(Movie M)
        {
            Movie temoM;
            int i;
            if (CurrentMovie.MoviesIMDBResultset.PopularTitles != null && CurrentMovie.MoviesIMDBResultset.PopularTitles.Exists(p => p.Id == M.Id))
            {
                temoM = CurrentMovie.MoviesIMDBResultset.PopularTitles.Find(p => p.Id == M.Id);
                if (!temoM.AlreadyDownloaded)
                {
                    M.AlreadyDownloaded = true;
                    i = CurrentMovie.MoviesIMDBResultset.PopularTitles.IndexOf(temoM);
                    CurrentMovie.MoviesIMDBResultset.PopularTitles.Remove(temoM);
                    CurrentMovie.MoviesIMDBResultset.PopularTitles.Insert(i, M);
                }
                return;
            }
            if (CurrentMovie.MoviesIMDBResultset.ExactMatches != null && CurrentMovie.MoviesIMDBResultset.ExactMatches.Exists(p => p.Id == M.Id))
            {
                temoM = CurrentMovie.MoviesIMDBResultset.ExactMatches.Find(p => p.Id == M.Id);
                if (!temoM.AlreadyDownloaded)
                {
                    M.AlreadyDownloaded = true;
                    i = CurrentMovie.MoviesIMDBResultset.ExactMatches.IndexOf(temoM);
                    CurrentMovie.MoviesIMDBResultset.ExactMatches.Remove(temoM);
                    CurrentMovie.MoviesIMDBResultset.ExactMatches.Insert(i, M);
                }
                return;
            }
            if (CurrentMovie.MoviesIMDBResultset.PartialMatches != null && CurrentMovie.MoviesIMDBResultset.PartialMatches.Exists(p => p.Id == M.Id))
            {
                temoM = CurrentMovie.MoviesIMDBResultset.PartialMatches.Find(p => p.Id == M.Id);
                if (!temoM.AlreadyDownloaded)
                {
                    M.AlreadyDownloaded = true;
                    i = CurrentMovie.MoviesIMDBResultset.PartialMatches.IndexOf(temoM);
                    CurrentMovie.MoviesIMDBResultset.PartialMatches.Remove(temoM);
                    CurrentMovie.MoviesIMDBResultset.PartialMatches.Insert(i, M);
                }
                return;
            }
        }

        private void btnSaveFilters_Click(object sender, EventArgs e)
        {
            XmlSerializer xser = new XmlSerializer(typeof(FiltersCollection));
            var theStream = File.Open(@"MovieFiltersContent.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            xser.Serialize(theStream, MFiltersCollection);
            theStream.Close();
            MessageBox.Show("It's Saved");

        }

        private void LoadFilters()
        {
            XmlSerializer xser = new XmlSerializer(typeof(FiltersCollection));
            if (File.Exists(@"MovieFiltersContent.xml"))
            {
                var theStream = File.Open(@"MovieFiltersContent.xml", FileMode.Open, FileAccess.Read);
                MFiltersCollection = (FiltersCollection)xser.Deserialize(theStream);
                theStream.Close();
            }
            ReBindFilters();
        }

        private void ApplyFiltersToFolders()
        {
            string temp;
            foreach (VMovie item in VMCollection)
            {
                if (item.MovieStatus != moviesStatuses.ImdbSynched)
                {
                    item.NewName = item.NewName.Replace('.', ' ').ToLower();
                    int tempYear = 0;

                    foreach (var filter in MFiltersCollection)
                    {
                        if (filter.Type == FilterType.Year && item.NewName.Contains(filter.FilterValue))
                            if (int.TryParse(filter.FilterValue, out tempYear))
                                item.YearByName = tempYear;

                        item.NewName = item.NewName.ToLower().Replace(filter.FilterValue.ToLower(), "");

                    }
                    temp = item.NewName.Split(' ').FirstOrDefault(p => p.StartsWith("-"));
                    if (!string.IsNullOrEmpty(temp))
                        item.NewName = item.NewName.Replace(temp, "");

                    item.NewName = item.NewName.TrimEnd();
                    string TitleCase = HelperClass.ToTitleCase(item.NewName);
                    item.NewName = TitleCase;
                    if (item.MovieSynhName != TitleCase)
                    {
                        item.MovieSynhName = TitleCase;
                        item.MovieStatus = moviesStatuses.None;
                    }
                }
            }
        }

        private void btnApplyFilters_Click(object sender, EventArgs e)
        {
            ApplyFiltersToFolders();
            dgvMoviesNamesInfo.Refresh();
        }


        private void btnApplyToFolders_Click(object sender, EventArgs e)
        {
            List<string> errorsFolders = new List<string>();
            foreach (VMovie item in movieFolderBindingSource.List)
            {
                switch (item.MovieStatus)
                {

                    case moviesStatuses.ImdbSynched:
                        try
                        {
                            item.NewName = ApplyNamePattern(item);
                            //item.MovieStatus = moviesStatuses.ImdbSynched;
                            //item.ID = item.NewName.GetHashCode();
                            if (Directory.Exists(moviesFolderPath) && !string.IsNullOrEmpty(item.NewName))
                            {
                                Directory.Move(Path.Combine(moviesFolderPath, item.OriginalName), Path.Combine(moviesFolderPath, item.NewName));
                            }
                            item.CurrentName = item.NewName;
                            item.MovieIMDBInfo.Poster.Save(Path.Combine(Path.Combine(moviesFolderPath, item.NewName), "Folder.jpg"));
                            item.FullPath = Path.Combine(moviesFolderPath, item.NewName);
                            item.SaveMovieConf();
                        }

                        catch (Exception exx)
                        {
                            errorsFolders.Add(item.OriginalName + " ( " + exx.Message + " )");
                        }
                        break;
                    case moviesStatuses.ImdbNotSynched:
                        item.SaveMovieConf();
                        break;
                    default:
                        break;
                }
            }

            if (errorsFolders.Count == 0)
                MessageBox.Show("Directory Names are Fixed");
            else
            {
                string errorMessage = "The Folowing Folders were not Renamed: \r\n ";
                foreach (var item in errorsFolders)
                {
                    errorMessage += "\r\n" + item;
                }
                //errorMessage += "\r\n \r\n ";
                MessageBox.Show(errorMessage);
            }

            VMCollection.Clear();
            FillMoviesFolders();
        }

        private string ApplyNamePattern(VMovie vm)
        {
            return String.Format("{0} ({1})", vm.NewName, vm.MovieIMDBInfo.UserRating);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            HelperClass.CopyFolder(@"E:\Movies", moviesFolderPath);
            MessageBox.Show("The Folder Titles successfully copied");

            FillMoviesFolders();
        }

        private void lstBoxMatches_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index != -1)
            {
                //
                // Draw the background of the ListBox control for each item.
                // Create a new Brush and initialize to a Black colored brush
                // by default.
                //
                e.DrawBackground();
                Brush myBrush = Brushes.Black;
                if (CurrentMovie.MovieIMDBInfo != null && ((Movie)((ListBox)sender).Items[e.Index]).Id == CurrentMovie.MovieIMDBInfo.Id)
                {
                    myBrush = Brushes.Green;
                }

                // Draw the current item text based on the current 
                // Font and the custom brush settings.
                //
                e.Graphics.DrawString(((Movie)(((ListBox)sender).Items[e.Index])).Title,
                    e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
                //
                // If the ListBox has focus, draw a focus rectangle 
                // around the selected item.
                //
                e.DrawFocusRectangle();
            }
        }


        private void dgvMoviesNamesInfo_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            VMovie tempMovie = (VMovie)movieFolderBindingSource.Current;
            if (tempMovie.NewName.TrimEnd() == tempMovie.CurrentName)
                tempMovie.NewName = tempMovie.NewName.TrimEnd();
            else
            {
                tempMovie.MovieStatus = moviesStatuses.None;
                tempMovie.MovieSynhName = tempMovie.NewName;
            }
        }

        private void tabMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabMain.SelectedIndex != -1)
            {
                if (tabMain.SelectedTab.Name == "tb_IMDB")
                {
                    imdbSynchronisation1.Bind(this.VMCollection);
                    imdbSynchronisation1.Enabled = true;
                }


            }
        }
    }
}